<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\CustomerDelivery;

use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class DeliveryFbaAjax {

    /**
     * 重新申请此单
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function backReapply($id){
        try{
            DB::beginTransaction();

            $deliveryObj = CustomerDelivery::query()->find($id);
            if($deliveryObj->status != CustomerDelivery::STATUS_DELIVERY_NO) throw new \Exception('状态有误!');
            if ($deliveryObj->detail->isEmpty()) throw new \Exception('订单有误!');

            foreach ($deliveryObj->detail as $detail){
                //更新(回写)订单详情
                $orderDetailObj = CustomerOrderDetails::query()->find($detail->order_detail_id);
                if (empty($orderDetailObj)) break;
                $orderDetailObj->apply_num -= $detail->apply_num;
                $num = $orderDetailObj->apply_num;
                if($num == 0){
                    $orderDetailObj->status =  CustomerOrderDetails::ORDER_DELIVERY_NO;    //1:未申请
                }else{
                    if($orderDetailObj->order_num > $num){
                        $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_PART;    //2:部分申请
                    }else{
                        $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_YES;    //3:完全申请
                    }
                }
                if(!$orderDetailObj->save()){
                    break;
                }
            }
            if(!$deliveryObj->delete()) throw new \Exception('重新申请失败!');

            DB::commit();
            return response()->json(['status' =>true, 'message' => '重新申请成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 重新申请此商品
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function backReapplyItem($id){
        try{
            DB::beginTransaction();

            $deliveryDetailObj = CustomerDeliveryDetail::query()->find($id);
            if($deliveryDetailObj->status != CustomerDeliveryDetail::STATUS_DELIVERY_NO) throw new \Exception('状态有误!');

            //更新(回写)订单详情
            $orderDetailObj = CustomerOrderDetails::query()->find($deliveryDetailObj->order_detail_id);
            if(empty($orderDetailObj)) throw new \Exception('订单详情异常!');

            $orderDetailObj->apply_num -= $deliveryDetailObj->apply_num;
            $num = $orderDetailObj->apply_num;
            if($num == 0){
                $orderDetailObj->status =  CustomerOrderDetails::ORDER_DELIVERY_NO;    //1:未申请
            }else{
                if($orderDetailObj->order_num > $num){
                    $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_PART;    //2:部分申请
                }else{
                    $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_YES;    //3:完全申请
                }
            }
            if(!$orderDetailObj->save()){
                throw new \Exception('申请失败!');
            }

            //清除旧数据（发货相关的信息）
            $detailCount = CustomerDeliveryDetail::query()
                ->where('delivery_no', $deliveryDetailObj->delivery_no)
                ->where('id','<>',$id)
                ->count();
            if($detailCount == 0){
                $deliveryObj = CustomerDelivery::query()->where('delivery_no', $deliveryDetailObj->delivery_no)->first();
                if(!$deliveryObj->delete()) throw new \Exception('申请失败-1!');
            }else{
                if(!$deliveryDetailObj->delete()) throw new \Exception('申请失败-2!');
            }

            DB::commit();
            return response()->json(['status' =>true, 'message' => '申请商品成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 标记商品ERROR
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function markErrorItem($id){
        try{
            DB::beginTransaction();

            //更新
            $detailObj = CustomerDeliveryDetail::query()->find($id);
            if($detailObj->error_status != CustomerDeliveryDetail::STATUS_NORMAL) throw new \Exception('状态有误!');

            $detailObj->error_status = CustomerDeliveryDetail::STATUS_ERROR; //异常状态：1:ERROR
            if(!$detailObj->save()){
                throw new \Exception('标记失败!');
            }

            DB::commit();
            return response()->json(['status' =>true, 'message' => '标记成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 撤销商品ERROR标记
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function revokeErrorItem($id){
        try{
            DB::beginTransaction();

            //更新
            $detailObj = CustomerDeliveryDetail::query()->find($id);
            if($detailObj->error_status != CustomerDeliveryDetail::STATUS_ERROR) throw new \Exception('状态有误!');

            $detailObj->error_status = CustomerDeliveryDetail::STATUS_NORMAL; //异常状态：0:正常
            if(!$detailObj->save()){
                throw new \Exception('撤销失败!');
            }

            DB::commit();
            return response()->json(['status' =>true, 'message' => '撤销成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * fba发货
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function markShipItem($param){

        try{
            DB::beginTransaction();

            if (empty($param)) throw new \Exception('发货单据不能为空!');

            $detailIdArr = explode(',', $param['ids']);
            if (empty($detailIdArr)) throw new \Exception('单据异常!');

            //发货
            foreach ($detailIdArr as $detailId) {
                //更新发货单详情
                $detailObj = CustomerDeliveryDetail::query()->find($detailId);
                if($detailObj->status != CustomerDeliveryDetail::STATUS_DELIVERY_NO) throw new \Exception('【'.$detailObj->delivery_no. '】发货详情状态异常!');
                $detailObj->ship_num += $detailObj->apply_num;
                $detailObj->status = CustomerDeliveryDetail::STATUS_DELIVERY_YES; //已发货
                $detailObj->delivered_at = date('Y-m-d H:i:s');
                if(!$detailObj->save()){
                    throw new \Exception('发货详情更新失败!');
                }

                //验证/匹配状态
                $deliveryDetailStatusArr = CustomerDeliveryDetail::query()
                    ->where(['delivery_no' => $detailObj->delivery_no])
                    ->pluck('status')
                    ->toArray();
                if(empty($deliveryDetailStatusArr)) throw new \Exception('状态异常!');
                $status = CustomerDeliveryDetail::extractStatus($deliveryDetailStatusArr);

                //更新发货单
                $deliveryObj = CustomerDelivery::query()->where(['delivery_no' => $detailObj->delivery_no])->first();
                if(empty($deliveryObj)) throw new \Exception('发货单异常!');
                $deliveryObj->status = $status; //业务状态 (1:待备货 2:已备货 3:待发货 4:部分发货 5:已发货)
                $deliveryObj->delivered_at = date('Y-m-d H:i:s');
                if(!$deliveryObj->save()){
                    throw new \Exception('发货失败!');
                }
            }

            DB::commit();
            return response()->json(['status' =>true, 'message' => '发货成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    //编辑物流
    public function modify($id){
        $deliveryDetail = CustomerDeliveryDetail::query()->find($id);
        $delivery = CustomerDelivery::query()->where('delivery_no',$deliveryDetail->delivery_no)->first();
        return view('customer-delivery.delivery-fba.modify',compact('id','delivery','deliveryDetail'));
    }

    /**
     * 更新物流
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doModify($param){
        try{

            if(!$param['account_id']) return response()->json(['status' => false, 'message' => '发货账号不能为空!']);
            if(!$param['seller_sku']) return response()->json(['status' => false, 'message' => '平台SKU不能为空!']);
            if(!isset($param['sync_status'])) return response()->json(['status' => false, 'message' => '同步状态不能为空!']);

            $deliveryDetailObj = CustomerDeliveryDetail::query()->find($param['id']);
            $deliveryObj = CustomerDelivery::query()->where('delivery_no', $deliveryDetailObj->delivery_no)->first();
            if(!$deliveryDetailObj || !$deliveryObj) return response()->json(['status' => false, 'message' => '单据异常!']);
            if(!in_array($deliveryObj->delivery_type, [1,2])) return response()->json(['status' => false, 'message' => '单据发货方式异常!']);
            if($deliveryObj->logistics_status == 2) return response()->json(['status' => false, 'message' => '操作失败：已经同步过了!']);

            DB::beginTransaction();

            //更新发货单
            if($deliveryDetailObj->sync_status == CustomerDeliveryDetail::SYNC_STATUS_YES){
                if(!$param['tracking_no']){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败：追踪号不能为空!']);
                }
                if(!$param['logistics_type']){
                    DB::rollBack();
                    return response()->json(['status' => false, 'message' => '操作失败：运输方式不能为空!']);
                }
                $deliveryObj->logistics_status = 2;
            }else{
                $deliveryObj->logistics_status = 1;
            }

            if(!$deliveryObj->save()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货单据,更新失败!']);
            }

            $logisticsFeeStatus = CustomerDeliveryDetail::LOGISTICS_FEE_NO;
            if (intval($param['total_weight']) > 0 || intval($param['total_weight']) > 0 || intval($param['other_fee']) > 0) {
                $logisticsFeeStatus = CustomerDeliveryDetail::LOGISTICS_FEE_YES;  //物流费用，已更新 (0:未更新 1:已更新)
            }

            //更新发货明细
            $deliveryDetailObj->account_id     = $param['account_id'];
            $deliveryDetailObj->seller_sku     = $param['seller_sku'];
            $deliveryDetailObj->tracking_no    = $param['tracking_no'];
            $deliveryDetailObj->logistics_type = $param['logistics_type'];
            $deliveryDetailObj->logistics_fee_status = $logisticsFeeStatus;
            $deliveryDetailObj->sync_status    = $param['sync_status'];
            if(!$deliveryDetailObj->save()){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货明细,更新失败!']);
            }

            DB::commit();
            return response()->json(['status' => true, 'message' => '物流编辑成功!']);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '物流编辑失败!']);
        }
    }

    /**
     * 同步物流状态
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function syncOutbound($param){
        try{

            if(empty($param['accountId'])) return response()->json(['status' => false, 'message' => '发货账号不能为空!']);
            if(empty($param['deliveryOrderNo'])) return response()->json(['status' => false, 'message' => '实际发货订单号异常!']);

            ////线下（本地）
            //if(is_local_env() == true) {
            //    $result = file_get_contents("http://www.api.cc/api/order/sync?account_id={$param['accountId']}&delivery_order_no={$param['deliveryOrderNo']}");
            //    if($result) return json_decode($result,true);
            //}

            //线上（正式）
            if(is_local_env() == false) {
                $result = file_get_contents("https://api.xinqianchao.com/api/order/sync?account_id={$param['accountId']}&delivery_order_no={$param['deliveryOrderNo']}");
                if($result) return json_decode($result,true);
            }

        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误!']);
        }
    }

}
